package com.tanhua.manage.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器是需要实现
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==========统一处理的token============="+request.getRequestURI());
        //1.先获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(token)){
            token = token.replace("Bearer ", "");
        }
        //2. 如果没有携带token，代表该用户没有登陆
        if(token==null){
            response.setStatus(401);
            return false;
        }

        //3. 如果已经携带了token，但是token找不到用户对象
        Admin admin = adminService.findAdminByToken(token);
        if(admin==null){
            response.setStatus(401);
            return false;
        }

        //4. token找到对应的用户，代表着该用户是登陆的。
        //问题： 如何把User对象传递给controller与service...
        AdminHolder.set(admin);

        return true;
    }
}
